package com.general.client.widgets.button;

import com.general.client.action.ActionHandler;
import com.general.client.basewidget.BaseWidget;
import com.general.client.bundle.CommonBundle;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;

public abstract class AbstractButton extends BaseWidget implements IButton {
	protected UiBinder<Widget, AbstractButton> uiBinder;

	@UiField
	protected FocusPanel mainPanel;

	@UiField
	protected InlineLabel innerText;

	@UiField
	protected CommonBundle common;

	protected boolean isEnabled = true;

	public UiBinder<Widget, AbstractButton> getUiBinder() {
		return ButtonBinders.grayButtonUiBinder;
	}

	public AbstractButton() {
		init();
		mainPanel.addFocusHandler(new FocusHandler() {
			@Override
			public void onFocus(FocusEvent event) {
				mainPanel.addStyleName(common.style().focused());
			}
		});
		mainPanel.addBlurHandler(new BlurHandler() {
			@Override
			public void onBlur(BlurEvent event) {
				mainPanel.removeStyleName(common.style().focused());
			}
		});
	}

	@Override
	public abstract HandlerRegistration addActionHandler(
			final ActionHandler handler);

	protected abstract void init();

	@Override
	public HandlerRegistration addKeyDownHandler(final KeyDownHandler handler) {
		return mainPanel.addKeyDownHandler(new KeyDownHandler() {

			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (isEnabled)
					handler.onKeyDown(event);
			}
		});
	}

	@Override
	public HandlerRegistration addBlurHandler(BlurHandler handler) {
		return mainPanel.addBlurHandler(handler);
	}

	@Override
	public void setFocus() {
		mainPanel.setFocus(true);
	}

	@Override
	public HasText getText() {
		return innerText;
	}

	protected void setUiBinder(UiBinder<Widget, AbstractButton> uiBinder) {
		this.uiBinder = uiBinder;
	}

	@Override
	public Widget asWidget() {
		return mainPanel;
	}

	@Override
	public void setEnabled(boolean isEnabled) {
		this.isEnabled = isEnabled;
		if (!isEnabled)
			mainPanel.addStyleName(common.style().disabled());
		else
			mainPanel.removeStyleName(common.style().disabled());
	}

	@Override
	public boolean isEnabled() {
		return isEnabled;
	}

}
